package com.strelitzia.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strelitzia.entity.MessageEntity;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.MessageService;
import com.strelitzia.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @create 2024/1/18 15:09
 */

@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping()
    public ResultVo getAllMessage() {
        ResultVo resultVo = new ResultVo();

        try {
            resultVo.setData(messageService.get());
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }
        return resultVo;
    }

    @GetMapping("/{fid}")
    public ResultVo getAllMessage(@PathVariable("fid") Integer fid) {
        ResultVo resultVo = new ResultVo();

        try {
            resultVo.setData(messageService.get(fid));
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }
        return resultVo;
    }

    @PostMapping()
    public ResultVo add(Integer fid, String content) {
        ResultVo resultVo = new ResultVo();
        try {
            messageService.add(fid, content);
            resultVo.setMsg("留言成功");
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }
        return resultVo;
    }

    @GetMapping("/del/{id}")
    public ResultVo del(@PathVariable("id") Integer id) {
        ResultVo resultVo = new ResultVo();
        try {
            messageService.removeById(id);
            resultVo.setMsg("删除留言成功");
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }
        return resultVo;
    }

    @GetMapping("/count/{id}")
    public Integer count(@PathVariable("id") Integer id) {
        return messageService.count(new QueryWrapper<MessageEntity>().eq("fid", id));
    }
}
